package com.changgou.seckill.web.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.seckill.feign.SecKillOrderFeign;
import com.changgou.seckill.web.aspect.AccessLimit;
import com.changgou.seckill.web.util.CookieUtil;
import com.changgou.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author LQQ
 * @Date 2020/3/18 20:49
 * @Version 1.0
 */
@RestController
@RequestMapping("/wseckillorder")
public class SecKillOrderController {
    @Autowired
    private SecKillOrderFeign secKillOrderFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 秒杀下单
     *
     * @param time
     * @param id
     * @return
     */
    @AccessLimit//限流,每秒访问两次这方法
    @RequestMapping("/add")
    public Result add(@RequestParam("time") String time, @RequestParam("id") Long id, @RequestParam("random") String random) {
        //实现秒杀下单接口隐藏
        String cookieValue = this.readCookie();

        String redisRandomCode = (String) redisTemplate.opsForValue().get("randomcode_" + cookieValue);

        if (StringUtils.isEmpty(redisRandomCode)) {
            return new Result(false, StatusCode.ERROR, "下单失败");
        }

        //前端传的和redis中的不匹配
        if (!random.equals(redisRandomCode)) {
            return new Result(false, StatusCode.ERROR, "下单失败");

        }

        Result result = secKillOrderFeign.add(time, id);
        return result;
    }

    /**
     * 生成随机字符串
     *
     * @return
     */

    @GetMapping("/getToken")
    @ResponseBody
    public String getToken() {
        String randomString = RandomUtil.getRandomString();
        //将随机数存入redis中
        String readCookie = this.readCookie();

        //过期时间5秒
        redisTemplate.opsForValue().set("randomcode_" + readCookie, randomString, 5, TimeUnit.SECONDS);

        return randomString;
    }


    private String readCookie() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //获取cookie中jti的值
        String jti = CookieUtil.readCookie(request, "uid").get("uid");

        return jti;
    }
}
